package com.unieagle.exam.account;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.unieagle.exam.app.ExamApplication;
import com.unieagle.exam.model.UserInfoResult;
import com.unieagle.exam.utils.SharedPreferenceUtils;

public class AccountManager {
    private static final String TAG = "AccountManager";

    private UserInfoResult mUserInfo;
    private Gson mGson;
    public AccountManager(){
        loadUserInfo();
    }
    public static AccountManager getInstance(){
        return ExamApplication.instance.getAccountMnager();
    }
    public boolean isLogin(){
        if(mUserInfo == null){
            return false;
        }
        if(TextUtils.isEmpty(mUserInfo.getAccess_token())){
            return false;
        }
        return true;
    }
    
    public void logout() {
    	mUserInfo = null;
    	SharedPreferenceUtils.setUserInfo(ExamApplication.instance.getApplicationContext(), "");
    }

    public UserInfoResult getUserInfo(){
        return mUserInfo;
    }

    public String getAccessToken(){
        return mUserInfo == null? "":mUserInfo.getAccess_token();
    }

    public long getAccountId(){
        return mUserInfo == null? -1:mUserInfo.getId();
    }

    public void updateUserInfoResult(UserInfoResult obj){
        mUserInfo = obj;
        saveUserInfo();
    }

    public String getUserName(){
        return  mUserInfo == null ? "" : mUserInfo.getName();
    }

    public String getTrailCount(){
        return mUserInfo == null ? "无限次":String.valueOf(mUserInfo.getTrail_count());
    }

    public String getCertificateAvatarUrl(){
        return mUserInfo == null ? "" : mUserInfo.getCertificate_avatar_url();
    }

    public String getCertificateFrontUrl(){
        return mUserInfo == null? null: mUserInfo.getCertificate_image_front_url();
    }

    public String getCertificateBackUrl(){
        return mUserInfo == null? null: mUserInfo.getCertificate_image_back_url();
    }

    private void saveUserInfo(){
        if(mUserInfo == null){
            return;
        }
        if(mGson == null){
            mGson = new Gson();
        }
        String json =  mGson.toJson(mUserInfo);
        SharedPreferenceUtils.setUserInfo(ExamApplication.instance.getApplicationContext(), json);
    }

    private void loadUserInfo(){
        String json =  SharedPreferenceUtils.getUserInfo(ExamApplication.instance.getApplicationContext());
        if(TextUtils.isEmpty(json)){
            return;
        }
        if(mGson == null){
            mGson = new Gson();
        }
        try{
            mUserInfo = mGson.fromJson(json, UserInfoResult.class);
        }catch (Exception e){
            Log.d(TAG, "loadUserInfo exception:" + e.toString());
        }
    }
}
